<?php

namespace common\models;

use Yii;
use common\models\Pay;

/**
 * This is the model class for table "pay".
 *
 * @property string $id
 * @property integer $user_id
 * @property string $money
 * @property integer $status
 * @property string $relation_id
 * @property string $create_time
 * @property string $update_time
 */
class Pay extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'pay';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'user_id', 'money', 'relation_id', 'create_time', 'update_time'], 'required'],
            [['id', 'user_id', 'status', 'relation_id'], 'integer'],
            [['money'], 'number'],
            [['create_time', 'update_time'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'user_username' => '用户账号',
            'user_id' => '用户编号',
            'money' => '支付金额',
            'status' => '支付状态',//1未支付2已支付',
            'relation_id' => '相关id',
            'create_time' => '创建时间',
            'update_time' => '更新时间',
        ];
    }

    public function getUser()
    {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }

    public static function itemAlias ($type, $code = NULL)
    {
        $_items = [
            'status' => [
                //''  =>'状态',
                '1' => "未支付",              
                '2' => "已支付",      
            ],
        ];

        if (isset($code))
            return isset($_items[$type][$code]) ? $_items[$type][$code] : false;
        else
            return isset($_items[$type]) ? $_items[$type] : false;
    }

    /*
    * 保存前执行的操作
    */
    public function beforeSave($insert) {
        if (parent::beforeSave($insert)) {
            //是否是新添加
            if($this->isNewRecord) {
                if(!$this->status) $this->status = 1;
                
                $this->create_time = date("Y-m-d H:i:s", time());
                $this->update_time = date("Y-m-d H:i:s", time());
            }else{
                $this->update_time = date("Y-m-d H:i:s", time());
            }
            return true;
        } else {
            return false;
        }
    } 
}
